import type { Response } from 'express';
import type { AuthenticatedRequest } from '../types/express';
import type { TransactionClient } from '../types/prisma-types';
import prisma from '../lib/prisma';

export class EvaluationController {
  async createEvaluation(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const { title, description, startDate, endDate, questionIds } = req.body;

      const evaluation = await prisma.$transaction(async (tx: TransactionClient) => {
        return tx.evaluation.create({
          data: {
            title,
            description,
            startDate: new Date(startDate),
            endDate: new Date(endDate),
            status: 'PENDING',
            creatorId: req.user!.id,
            questions: {
              connect: questionIds.map((id: string) => ({ id }))
            }
          },
          include: {
            questions: true
          }
        });
      });

      res.status(201).json(evaluation);
    } catch (error) {
      console.error('创建评估失败:', error);
      res.status(500).json({ error: '创建评估失败' });
    }
  }

  async submitAnswer(req: AuthenticatedRequest, res: Response): Promise<void> {
    const { evaluationId, questionId, answer } = req.body;
    
    try {
      const submission = await prisma.submission.create({
        data: {
          answer,
          score: 0,
          userId: req.user!.id,
          questionId,
          evaluationId
        },
        include: {
          question: true,
          evaluation: true
        }
      });

      res.status(201).json(submission);
    } catch (error) {
      console.error('提交答案失败:', error);
      res.status(500).json({ error: '提交答案失败' });
    }
  }

  async gradeSubmission(req: AuthenticatedRequest, res: Response): Promise<void> {
    const { submissionId, score, feedback } = req.body;

    try {
      const submission = await prisma.submission.update({
        where: { id: submissionId },
        data: {
          score: Number(score),
          feedback
        },
        include: {
          question: true,
          evaluation: true
        }
      });

      res.status(200).json(submission);
    } catch (error) {
      console.error('评分失败:', error);
      res.status(500).json({ error: '评分失败' });
    }
  }

  async getEvaluations(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const evaluations = await prisma.evaluation.findMany({
        where: {
          creatorId: req.user!.id
        },
        include: {
          questions: true,
          submissions: {
            where: {
              userId: req.user!.id
            }
          }
        }
      });

      res.status(200).json(evaluations);
    } catch (error) {
      console.error('获取评估列表失败:', error);
      res.status(500).json({ error: '获取评估列表失败' });
    }
  }

  async getEvaluation(req: AuthenticatedRequest, res: Response): Promise<void> {
    const { id } = req.params;

    try {
      const evaluation = await prisma.evaluation.findUnique({
        where: { id },
        include: {
          questions: true,
          submissions: {
            where: {
              userId: req.user!.id
            }
          }
        }
      });

      if (!evaluation) {
        res.status(404).json({ error: '未找到该评估' });
        return;
      }

      res.status(200).json(evaluation);
    } catch (error) {
      console.error('获取评估详情失败:', error);
      res.status(500).json({ error: '获取评估详情失败' });
    }
  }
}

export default new EvaluationController();
